
//数组处理工具
import _function from "./_function";
import _object from "./_object";


//一维排序函数
let __oneSort = function (a, b, filter = true) {

  let v = _function._compare(a, b);
  return filter ? v : -v;
};

//二维排序函数
let __twoSort = function (a, b, filter) {

  //逐一对比属性
  for (let k in filter)
  {
    let v = _function._compare(a[k], b[k]);
    if (v === 0) continue;
    return filter[k] ? v : -v;
  }

  return 0;
};

let _array = {

  //主键查找
  _pk_find: function (data, filter, pk) {

    for (let i = 0, l = data.length; i < l; i++)
    {
      if (data[i][pk] == filter)
      return i;
    }

    return -1;
  },

  //联合键查找
  _uk_find: function (data, filter) {

    if (typeof filter != "object" || _object._length(data) === 0)
    return -1;

    first:
    for (let i = 0, l = data.length; i < l; i++)
    {
      let r = true;
      second:
      for (let k in filter)
      {
        if (filter[k] != data[i][k])
        {
          r = false;
          break second;
        }
      }

      if (r === true)
      return i;
    }

    return -1;
  },

  //多键查找
  _mk_find: function (data, filter) {

    let keys = [];
    if (typeof filter != "object" || _object._length(data) === 0)
    return keys;

    first:
    for (let i = 0, l = data.length; i < l; i++)
    {
      let r = true;
      second:
      for (let k in filter)
      {
        if (filter[k] != data[i][k])
        {
          r = false;
          break second;
        }
      }

      if (r === true)
      keys.push(i);
    }

    return keys;
  },

  //正向排序(true-正序|false-倒序|object-二维)
  _sort: function (data, filter = true) {

    let callback = null;
    if (typeof filter == "boolean")
    {
      //一维
      callback = __oneSort;
    } else
    if (typeof filter == "object" && _object._length(filter) > 0)
    {
      //二维
      callback = __twoSort;
    } else

    {
      //异常
      throw new Error("filter is not valid:" + filter);
    }

    data.sort(function (a, b) {
      return callback(a, b, filter);
    });
  },

  //反向排序
  _rsort: function (data) {

    if (typeof data == "object" && _object._length(data) > 0)
    data.reverse();

    return data;
  },

  //单数组去重
  _unique: function (data) {
    let r = [];
    for (let i = 0, l = data.length; i < l; i++)
    {
      for (let j = i + 1; j < l; j++)
      if (data[i] === data[j]) j = ++i;

      r.push(data[i]);
    }
    return r;
  },

  //数组不去重合并
  _no_de_merge: function () {

    return [].concat.apply(this, arguments);
  },

  //数组去重合并
  _de_merge: function () {
    let arr = [];
    if (arguments.length > 0)
    {
      for (let i = 0, l = arguments.length; i < l; i++)
      {
        if (typeof arguments[i] == 'object')
        {
          for (let j = 0, ll = arguments[i].length; j < ll; j++)
          {
            if (arr.indexOf(arguments[i][j]) === -1)
            arr.push(arguments[i][j]);
          }
        }
      }
    }
    return arr;
  }
};

//导出
export default _array;